<template>
  <view class="login">
    <div class="title">
      <div class="logo">奇特智居</div>
      <img
        src="cloud://dev-304ml.6465-dev-304ml-1300481250/banner/banner2.jpg"
      />
      <h2>用户登录</h2>
    </div>
    <nut-form :model-value="formData" ref="ruleForm">
      <nut-form-item
        label="电话"
        prop="tel"
        required
        :rules="[
          { required: true, message: '请填写电话号码' },
          { validator: telValidator, message: '电话格式不正确' },
        ]"
      >
        <input
          class="nut-input-text"
          v-model="formData.tel"
          placeholder="请填写电话号码"
          type="text"
          @blur="blurValidate('tel')"
        />
      </nut-form-item>
      <nut-form-item
        label="密码"
        prop="pwd"
        required
        :rules="[{ required: true, message: '密码不能为空' }]"
      >
        <input
          class="nut-input-text"
          v-model="formData.pwd"
          placeholder="请填写密码"
          type="password"
          @blur="blurValidate('pwd')"
        />
      </nut-form-item>
    </nut-form>
    <nut-row style="margin-top: 30px">
      <nut-col :span="4">&nbsp;</nut-col>
      <nut-col :span="16">
        <nut-button type="primary" style="width: 100%" @click="submit()"
          >登录</nut-button
        >
      </nut-col>
      <nut-col :span="4">&nbsp;</nut-col>
    </nut-row>
  </view>

  <nut-cell
    title="新用户注册"
    style="position: absolute; bottom: 0"
    @click="goRegister"
  >
  </nut-cell>
</template>
<script lang="ts">
import Taro from "@tarojs/taro";
import { ref, reactive } from "vue";
import apiConfig from "../../services/apiConfig";
import userService from "../../services/userService";

function getUserInfo() {
  const token = Taro.getStorageSync("access_token");
  if (token) {
    Taro.showLoading({ title: "加载中..." });
    Taro.request({
      method: "GET",
      url: apiConfig.authUrl + "/checkLogin",
      header: {
        "content-type": "application/x-www-form-urlencoded",
        token: token,
      },
    }).then((res) => {
      Taro.hideLoading();
      if (res.statusCode == 200 && res.data) {
        Taro.setStorage({
          key: "token_info",
          data: res.data.data,
        });

        Taro.reLaunch({
          url: "/pages/index/index",
        });
      }
    });
    return;
  }
}

export default {
  beforeMount() {
    getUserInfo();
  },
  setup() {
    const formData = reactive({
      tel: "",
      pwd: "",
    });
    const validate = (item: any) => {
      console.log(item);
    };
    const ruleForm = ref<any>(null);

    const submit = () => {
      ruleForm.value.validate().then(({ valid, errors }: any) => {
        if (valid) {
          Taro.showLoading({ title: "加载中..." });
          console.log("success", formData);
          Taro.request({
            method: "POST",
            url: apiConfig.authUrl + "/token",
            data: {
              grant_type: "password",
              client_id: "iotkit",
              username: formData.tel,
              password: formData.pwd,
            },
            header: {
              "content-type": "application/x-www-form-urlencoded",
            },
          }).then((res) => {
            Taro.hideLoading();
            if (res.statusCode != 200) {
              Taro.showToast({
                title: "登录失败",
                icon: "error",
                duration: 2000,
              });
              return;
            }
            let data = res.data;
            console.log(data);
            Taro.setStorage({
              key: "access_token",
              data: data.access_token,
            });

            //登录时生成唯一客户端ID
            Taro.setStorage({
              key: "client_id",
              data: new Date().getTime().toString(),
            });

            //获取当前用户信息
            getUserInfo();

            //取用户当前家庭
            userService.fetchHome();

            Taro.reLaunch({
              url: "/pages/index/index",
            });
          });
          // url: "https://auth.iotkit.cc/realms/iotkit/protocol/openid-connect/token",
        } else {
          console.log("error submit!!", errors);
        }
      });
    };
    const reset = () => {
      ruleForm.value.reset();
    };
    // 失去焦点校验
    const blurValidate = (prop: string) => {
      ruleForm.value.validate(prop).then(({ valid, errors }: any) => {
        if (valid) {
          console.log("success", formData);
        } else {
          console.log("error submit!!", errors);
        }
      });
    };
    const telValidator = (val: string) =>
      /^400(-?)[0-9]{7}$|^1\d{10}$|^0[0-9]{2,3}-[0-9]{7,8}$/.test(val);

    function goRegister() {
      Taro.navigateTo({
        url: "/pages/login/register",
      });
    }

    return {
      ruleForm,
      formData,
      validate,
      telValidator,
      blurValidate,
      submit,
      reset,
      goRegister,
    };
  },
};
</script>

<style lang="scss">
.login {
  height: 100%;
  width: 80%;
  padding: 0 10%;
  .title {
    height: 300px;
    text-align: center;
    font-size: 24px;
    padding: 10px 10px;
    .logo {
      position: absolute;
      left: 0;
      width: 100%;
      height: 200px;
      padding-top: 60px;
      color: #fff;
      text-shadow: #999 1px 1px 1px;
    }

    img {
      width: 100%;
      height: 200px;
      margin-bottom: 50px;
      border-radius: 20px;
    }
  }
}
</style>